# coding=utf-8
import hashlib
import re
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.forms.models import model_to_dict

from common.services import SendMessage
from models import User
from forms import *


class UserService:
    def __init__(self):
        self.user = None

    def login(self, username, password):
        from_user = self.__match_user_name(username)
        password = hashlib.sha1(password).hexdigest()
        if from_user is None:
            return False
        if from_user.get('key') is 'email':
            self.email_login(from_user.get('data'), password)
        elif from_user.get('key') is 'phone':
            self.phone_login(from_user.get('data'), password)
        return True if self.user is not None else False

    def edit_user(self):
        self.user.save()
        return True

    def create_user(self, user_data):
        user_form = UserForm(user_data)
        if user_form.is_valid():
            # 先保存数据，然后发送验证
            self.user = user_form.save()
            user_private = UserPrivate(user=self.user)
            user_private.cash = 1000
            user_private.save()

            # todo 发送短信或是邮箱验证码
            # todo 队列处理发送验证码
            if user_form.cleaned_data.get('username') == 'email':
                link_email = hashlib.sha1(self.user.email).hexdigest()
                link = reverse('mailbox', args=(link_email, self.user.pk))
                SendMessage().send_verify_mail(
                    '注册验证', '点击链接验证',
                    'pfadai@163.com', self.user.email, link
                )

            return {'status': True, 'msg': ''}
        else:
            return {'status': False, 'msg': user_form.errors}

    def get_user(self, uid):
        if uid is None or uid == 0:
            self.user = None
        try:
            self.user = User.objects.get(pk=uid)
        except ObjectDoesNotExist:
            self.user = None

    def get_user_by_email(self, email):
        try:
            self.user = User.objects.get(email=email)
        except ObjectDoesNotExist:
            self.user = None

    def logout(self):
        self.user = None
        return True

    def verification_email(self, uid, email):
        if uid is None or email is None:
            raise Exception('参数错误')
        self.user = User.objects.get(pk=uid)
        if hashlib.sha1(self.user.email).hexdigest() == email:
            form = ContactVerifyForm(
                {
                    'username': email,
                    'method': 'email'
                },
                instance=self.user
            )
            print form.is_valid()
            if form.is_valid():
                form.save()
                return True
            else:
                print form.errors
                return False
        else:
            return False

    def real_name(self, uid, id_card, photo_front, photo_back):
        self.get_user(uid)
        if self.user is None:
            return {'status': False, 'msg': 'error_user'}
        form = UserRealNameVerifyForm(
            {
                'id_card': id_card,
                'photo_front': photo_front,
                'photo_back': photo_back,
            },
            instance=self.user
        )
        # 当数据库中存在文件时，django不会再去判断上传是否成功
        if form.is_valid():
            form.save()
            return {'status': True, 'msg': ''}
        return {'status': False, 'msg': form.errors}

    def email_reset(self):
        # todo 根据邮箱进行密码重置
        pass

    def email_login(self, username, password):
        try:
            self.user = User.objects.get(email=username, password=password)
        except ObjectDoesNotExist:
            self.user = None

    def phone_login(self, username, password):
        try:
            self.user = User.objects.get(phone=username, password=password)
        except ObjectDoesNotExist:
            self.user = None

    @staticmethod
    def __match_user_name(username):
        email = re.match('^.+@(\\[?)[a-zA-Z0-9\\-.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$', username)
        phone = re.match('^\d{11}$', username)

        if email and not phone:
            return {'key': 'email', 'data': email.string}
        elif phone and not email:
            return {'key': 'phone', 'data': phone.string}
        else:
            return None


class UserPrivateService(object):

    @classmethod
    def get_user_private(cls, user_id):
        try:
            user_private = UserPrivate.objects.get(user_id=user_id)
            user_private = model_to_dict(user_private)
            user_private['photo_front'] = str(user_private['photo_front'])
            user_private['photo_back'] = str(user_private['photo_back'])
            return user_private
        except ObjectDoesNotExist:
            return None
